package com.tjmc.recruit.common.core.util;

import cn.hutool.core.util.PhoneUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.tjmc.recruit.common.core.config.SmsConfig;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
public class AliSmsUtil {
    public static void send(SmsConfig config, String phone, String paramJson) {
        // 需要的参数：
        // 1 短信签名
        // 2 短信模板ID
        // 3 accessKeyId、accessKeySecret
        // 4 发送手机号-需验证合法性
        // 5 短信内容参数
        if (config == null) {
            log.error("sms config is null");
            return;
        }
        log.info("短信配置参数：短信accessId:{}, 短信accessKey:{}, 短信签名:{}, 短信模板：{}", config.getAccessId(), config.getAccessKey(), config.getSignName(), config.getTemplateCode());
        if (!PhoneUtil.isPhone(phone)) {
            log.error("发送手机号不合法");
            return;
        }
        log.info("短信参数信息: {}", paramJson);
        try {
            // Configure Credentials authentication information, including ak, secret, token
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    //"LTAI5tPzYuz3hWsc79jSqeTz"
                    .accessKeyId(config.getAccessId())
                    //"MRLpKWteonB95Ng4RLEpoWdlrjeNi2"
                    .accessKeySecret(config.getAccessKey())
//                    .securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                    .build());
            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // Region ID
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(config.getSignName())
                    .templateCode(config.getTemplateCode())
                    .phoneNumbers(phone)
                    .templateParam(paramJson)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            log.info("短信发送结果：{}", resp);
            // Finally, close the client
            client.close();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
